package com.attempt.grab.service;

import com.alibaba.fastjson.JSON;
import com.attempt.grab.constant.Constants;
import com.attempt.grab.constant.Payload;
import com.attempt.grab.constant.WebSocketSessionSender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author xuhaifeng
 * @since 2022年02月25日 下午 1:28
 */
@Slf4j
@Component
public class GrabService implements WebSocketHandler {
    private final RobotService robotService;
    /**
     * Web套接字会话发送者 存储容器
     */
    private static final ConcurrentHashMap<String, WebSocketSessionSender> SENDER_MAP = new ConcurrentHashMap<>();

    @Autowired
    public GrabService(RobotService robotService) {this.robotService = robotService;}

    /**
     * 获取Grab操作者
     *
     * @return SenderMap
     */
    public static ConcurrentHashMap<String, WebSocketSessionSender> getSenderMap() {
        return SENDER_MAP;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        final String userId = String.valueOf(session.getAttributes().get(Constants.USER_ID_KEY));
        log.info("用户:{},连接Grab", userId);
        SENDER_MAP.put(userId, new WebSocketSessionSender(session));
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) {
        /* 记录最后一后键盘或鼠标事件的到达时间 */
        robotService.setLasActionTime(System.currentTimeMillis());
        if (message instanceof TextMessage) {
            robotService.actionEvent(JSON.parseObject(String.valueOf(message.getPayload()), Payload.class));
        } else if (message instanceof BinaryMessage) {
            new WebSocketSessionSender(session).sendData((byte[]) message.getPayload());
        } else if (message instanceof PingMessage) {
            new WebSocketSessionSender(session).sendPongData();
        } else {
            log.error("意外的WebSocket消息类型: {}", session);
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) {
        log.error("数据传输错误");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
        final String userId = String.valueOf(session.getAttributes().get(Constants.USER_ID_KEY));
        log.info("用户:{}断开Grab连接", userId);
        SENDER_MAP.remove(userId);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
